package com.kws.payment.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.chinaums.open.api.OpenApiCache;
import com.chinaums.open.api.OpenApiContext;
import com.chinaums.open.api.constants.ConfigBean;
import com.chinaums.open.api.internal.util.http.HttpTransport;
import com.kws.common.core.exception.ServiceException;
import com.kws.common.core.utils.StringUtils;
import com.kws.payment.dao.CreateUnionPayMiniOrderRq;
import com.kws.payment.dao.UnionPayMiniOrderRq;
import com.kws.payment.dao.info.CreateAppUnionPayOrderInfo;
import com.kws.payment.dao.info.CreateWXUnionPayOrderInfo;
import com.kws.payment.service.UnionPayMiniService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * <b>UnionPayMiniServiceImpl</b>
 *
 * @description: UnionPayMiniServiceImpl <br>
 * @date: 2024/12/26 18:07 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class UnionPayMiniServiceImpl implements UnionPayMiniService {
    private static final Logger logger = LoggerFactory.getLogger(UnionPayMiniServiceImpl.class);

    /**
     * 银联分配appid
     */
    public String appId = "8a81c1bf9325ea850194445c10ee072e";

    /**
     * 银联分配appkey
     */
    public String appKey = "ca2c7ed68ac14fa5b087665656adb65c";

    /**
     * 银联分配来源编号
     */
    public String sourceNumber = "3CKR";

    /**
     * 商户号
     */
    public String mid = "89861084900230G";

    /**
     * 终端号
     */
    public String tid = "00000001";

    /**
     * 微信子商户appId
     */
    public String WXAppId = "wxd862c8568f4fd046";

    /**
     * 银联支付微信下单地址
     */
    public String unionPayAppWeixinOrderUrl = "https://api-mop.chinaums.com/v1/netpay/wx/unified-order";

    @Override
    public CreateWXUnionPayOrderInfo createMiniUnionPayOrder(CreateUnionPayMiniOrderRq rq)  throws Exception{
        UnionPayMiniOrderRq unionPayMiniOrderRq = new UnionPayMiniOrderRq();
        BeanUtil.copyProperties(rq, unionPayMiniOrderRq);
        unionPayMiniOrderRq.setRequestTimestamp(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMATTER));
        unionPayMiniOrderRq.setMid(mid);
        unionPayMiniOrderRq.setTid(tid);
        unionPayMiniOrderRq.setSubAppId(WXAppId);
        unionPayMiniOrderRq.setTradeType("MINI");
        unionPayMiniOrderRq.setMerOrderId(sourceNumber + rq.getOrderNo());
        //所有订单都需要走分账（订单要分账必须带分账标识，而且不打分账标识，交易资金全进平台账户）
        //unionPayMiniOrderRq.setDivisionFlag(true);

        ConfigBean configBean = new ConfigBean();
        OpenApiContext context = new OpenApiContext();
        context.setStartTime(System.currentTimeMillis());
        context.setRequestId(UUID.randomUUID().toString().replace("-", ""));
        context.setOpenServUrl(unionPayAppWeixinOrderUrl.split("/v")[0].concat("/"));
        context.setApiServiceUrl(unionPayAppWeixinOrderUrl);
        context.setVersion(unionPayAppWeixinOrderUrl.split("/")[3]);
        context.setAppId(appId);
        context.setAppKey(appKey);
        context.setConfigBean(configBean);
        context.setServiceCode(unionPayAppWeixinOrderUrl.split("/v")[1].substring(1));
        OpenApiCache.getCurrentToken(context);

        //发起微信下单请求
        String respond = HttpTransport.getInstance().doPost(context, JSONUtil.toJsonStr(unionPayMiniOrderRq));
        logger.info("获取微信下单返回结果：" + respond);
        if (StringUtils.isEmpty(respond)) {
            throw new ServiceException("下单失败！", 30001);
        }
        CreateWXUnionPayOrderInfo info = JSONUtil.toBean(JSONUtil.parseObj(respond), CreateWXUnionPayOrderInfo.class);
        if (!"SUCCESS".equals(info.getErrCode())) {
            throw new ServiceException(info.getErrMsg(), 30002);
        }
        return info;
    }
}
